import urllib
import cgi
import re
import logging

from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
from google.appengine.ext import webapp
from datetime import datetime
import time

try:
  # This is where simplejson lives on App Engine
  from django.utils import simplejson
except (ImportError):
  import simplejson

DATE_FORMAT = "%a, %d %b %Y %H:%M:%S GMT"

class Item(db.Model):
  content = db.TextProperty(required=True)
  author = db.TextProperty(required=True)
  link = db.TextProperty(required=True)
  updated = db.FloatProperty(required=True)

def make_item(content, author, link, updated):
  # Add new item
  item = Item(content=content, author=author, link=link, updated=updated)
  item.put()

class UpdatesHandler(webapp.RequestHandler):
  def get(self):
    if self.request.get('updated', 0) != 0:
      query = Item.all()
      query.filter('updated >', float(self.request.get('updated'))).order('-updated')
      results = query.fetch(limit=100)
    else:
      query = Item.all()
      results = query.order('-updated').fetch(limit=10)
    
    json = simplejson.dumps([{
      "content": result.content,
      "author": result.author,
      "link": result.link,
      "updated": result.updated
    } for result in results])
    
    logging.info(json)
    self.response.headers['Content-Type'] = \
      'application/json; charset=utf-8'
    self.response.out.write(json)